package cc.flyflow.core.controller;

import cc.flyflow.common.dto.third.*;
import cc.flyflow.common.utils.JsonUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


//@RestController
@RequestMapping("test/http")
public class TestHttpController {

    private List<UserDto> userList = new ArrayList<>();
    private List<DeptDto> deptList = new ArrayList<>();
    private List<RoleDto> roleList = new ArrayList<>();
    private List<UserRole> userRoleList = new ArrayList<>();
    private List<UserFieldDto> userFieldList = new ArrayList<>();

    private Map<String, Object> userFieldDataList = new HashMap<>();

    @PostConstruct
    public void init() {

        if (FileUtil.exist("/tmp/user.json")) {
            {
                String s = FileUtil.readUtf8String("/tmp/user.json");
                userList.addAll(JsonUtil.parseArray(s, UserDto.class));
            }
            {
                String s = FileUtil.readUtf8String("/tmp/dept.json");
                deptList.addAll(JsonUtil.parseArray(s, DeptDto.class));
            }
            {
                String s = FileUtil.readUtf8String("/tmp/role.json");
                roleList.addAll(JsonUtil.parseArray(s, RoleDto.class));
            }
            {
                String s = FileUtil.readUtf8String("/tmp/userrole.json");
                userRoleList.addAll(JsonUtil.parseArray(s, UserRole.class));
            }
            {
                String s = FileUtil.readUtf8String("/tmp/userfield.json");
                userFieldList.addAll(JsonUtil.parseArray(s, UserFieldDto.class));
            }
            {
                String s = FileUtil.readUtf8String("/tmp/userfielddata.json");

                Map<String, Object> stringObjectMap = JsonUtil.parseObject(s, new JsonUtil.TypeReference<Map<String, Object>>() {
                });
                userFieldDataList.putAll(stringObjectMap);
            }

            return;
        }

        {
            RoleDto d = RoleDto.builder().id("role1").name("角色1").status(1).build();
            roleList.add(d);
        }
        {
            RoleDto d = RoleDto.builder().id("role2").name("角色2").status(1).build();
            roleList.add(d);
        }
        {
            RoleDto d = RoleDto.builder().id("role3").name("角色3").status(1).build();
            roleList.add(d);
        }
        {
            DeptDto d =
                    DeptDto.builder().id("dept1").name("部门1").parentId("0").leaderUserIdList(CollUtil.newArrayList("user1")).status(1).build();
            deptList.add(d);
        }
        {
            DeptDto d =
                    DeptDto.builder().id("dept2").name("部门2").parentId("dept1").leaderUserIdList(CollUtil.newArrayList("user11")).status(1).build();
            deptList.add(d);
        }
        {
            DeptDto d =
                    DeptDto.builder().id("dept3").name("部门3").parentId("dept1").leaderUserIdList(CollUtil.newArrayList("user15")).status(1).build();
            deptList.add(d);
        }
        {
            DeptDto d =
                    DeptDto.builder().id("dept4").name("部门4").parentId("dept2").leaderUserIdList(CollUtil.newArrayList("user21")).status(1).build();
            deptList.add(d);
        }
        {
            DeptDto d =
                    DeptDto.builder().id("dept5").name("部门5").parentId("dept3").leaderUserIdList(CollUtil.newArrayList("user45")).status(1).build();
            deptList.add(d);
        }
        //用户属性
        {
            UserFieldDto userFieldDto = new UserFieldDto();
            userFieldDto.setName("年龄");
            userFieldDto.setType("Number");
            userFieldDto.setRequired(true);
            userFieldDto.setProps(JsonUtil.toJSONString(Dict.create().set("radixNum", 3)));
            userFieldDto.setKey("flyflow_age");
            userFieldList.add(userFieldDto);

        }
        {
            UserFieldDto userFieldDto = new UserFieldDto();
            userFieldDto.setName("住址");
            userFieldDto.setType("Input");
            userFieldDto.setRequired(true);
            userFieldDto.setProps("");
            userFieldDto.setKey("flyflow_address");
            userFieldList.add(userFieldDto);

        }
        for (long k = 1; k <= 100; k++) {
            long deptId = RandomUtil.randomLong(0, deptList.size()) + 1;
            long roleId = RandomUtil.randomLong(0, roleList.size()) + 1;

            UserDto u =
                    UserDto.builder().id("user" + k).name("用户" + k).token(IdUtil.fastSimpleUUID()).avatarUrl("https" +
                            "://f" +
                            ".ittool.cc/pic/m" +
                            ".jpg").deptIdList(CollUtil.newArrayList("dept" + deptId)).status(1).build();
            userList.add(u);

            {
                UserRole userRole = UserRole.builder().roleId("role" + roleId).userId(u.getId()).build();
                userRoleList.add(userRole);
            }
            {


                userFieldDataList.put(u.getId(), Dict.create().set("flyflow_address", RandomUtil.randomString(10)).set("flyflow_age",
                        RandomUtil.randomInt(1,
                                100)));

            }
        }

        FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(userList), "/tmp/user.json");
        FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(deptList), "/tmp/dept.json");
        FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(roleList), "/tmp/role.json");
        FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(userRoleList), "/tmp/userrole.json");
        FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(userFieldList), "/tmp/userfield.json");
        FileUtil.writeUtf8String(JSONUtil.toJsonPrettyStr(userFieldDataList), "/tmp/userfielddata.json");

    }

    @PostMapping("userList")
    public PageResultDto<UserDto> userList(@RequestBody UserQueryDto userQueryDto) {


        PageResultDto<UserDto> pageResultDto = new PageResultDto<>((long) userList.size(), userList);

        return pageResultDto;
    }

    @PostMapping("userIdListByRoleIdListAndDeptIdList")
    public List<String> userIdListByRoleIdListAndDeptIdList(@RequestBody UserQueryDto userQueryDto) {

        List<String> list = new ArrayList<>();

        List<String> deptIdList = userQueryDto.getDeptIdList();
        List<String> roleIdList = userQueryDto.getRoleIdList();
        if (CollUtil.isNotEmpty(roleIdList)) {
            List<String> collect = userRoleList.stream().filter(w -> roleIdList.contains(w.getRoleId())).map(w -> w.getUserId()).collect(Collectors.toList());
            if (CollUtil.isEmpty(collect)) {
                return list;
            }
            list.addAll(collect);

        }
        if (CollUtil.isNotEmpty(deptIdList)) {
            List<String> collect = userList.stream()
                    .filter(w-> !CollUtil.intersection(deptIdList, w.getDeptIdList()).isEmpty())
                    .map(w -> w.getId()).collect(Collectors.toList());
            if (CollUtil.isEmpty(collect)) {
                return new ArrayList<>();
            }
            if (list.size() > 0) {
                list.retainAll(collect);
            }
        }

        return list;
    }

    @PostMapping("roleIdListByUserId")
    public List<String> roleIdListByUserId(@RequestBody Map map) {

        String userId = MapUtil.getStr(map, "userId");


        List<String> collect =
                userRoleList.stream().filter(w -> w.getUserId().equals(userId)).map(w -> w.getRoleId()).collect(Collectors.toList());


        return collect;
    }
    @PostMapping("roleAll")
    public List<RoleDto> roleAll() {



        return roleList;
    }


    @PostMapping("userIdByToken")
    public String userIdByToken(@RequestBody Map map) {

        String token = MapUtil.getStr(map, "token");

        return userList.stream().filter(w -> StrUtil.equals(w.getToken(), token)).findFirst().get().getId();

    }



    @PostMapping("deptListByParentDeptId")
    public List<DeptDto> deptListByParentDeptId(@RequestBody Map map) {
        String parentDeptId = MapUtil.getStr(map, "parentDeptId");

        if (StrUtil.isBlank(parentDeptId)) {
            return deptList;
        }

        return deptList.stream().filter(w -> w.getParentId().equals(parentDeptId)).collect(Collectors.toList());
    }




    @PostMapping("userListByDeptId")
    public List<UserDto> userListByDeptId(@RequestBody Map map) {
        String deptId = MapUtil.getStr(map, "deptId");

        return userList.stream().filter(w->w.getDeptIdList().contains(deptId)).collect(Collectors.toList());

    }



    @PostMapping("userById")
    public UserDto userById(@RequestBody Map map) {
        String userId = MapUtil.getStr(map, "userId");

        return userList.stream().filter(w -> userId.equals(w.getId())).findFirst().orElse(null);

    }









    @PostMapping("deptById")
    public DeptDto deptById(@RequestBody Map map) {
        String deptId = MapUtil.getStr(map, "deptId");

        return deptList.stream().filter(w -> deptId.equals(w.getId())).findFirst().get();

    }










    @GetMapping("userByName")
    public List<UserDto> userByName(@RequestBody Map map) {
        String name = MapUtil.getStr(map, "name");


        return userList.stream().filter(w -> w.getName().contains(name)).collect(Collectors.toList());
    }








    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    private static class UserRole {
        private String userId;
        private String roleId;


    }

}
